<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>8x8</title>
	<style type="text/css">
		.dots {
			width: 280px;
			margin: 20px auto;
			display: flex;
		  flex-direction: row;
		  flex-wrap: wrap;
		}
		.dots > div {
			width: 30px;
			height: 30px;
			border: 1px solid #ccc;
			margin: 1px;
			cursor: pointer;
		}
		.red {
			background: #ff5757;
		}
		.hex {
			text-align: center;
		}
		.hex input {
			border: none;
			width: 220px;
		}
	</style>
</head>
<body>
	<div class="dots"></div>
	<p class="hex">十六进制：<input /><button id="btn">复制</button></p>
</body>
<script type="text/javascript">
	// 适用于 micropython keyes
	let data8 = [
		[0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0]
	]
	let $hex = document.querySelector('.hex > input');
	let $dots = document.querySelector('.dots')
	let $btn = document.querySelector('#btn')
	// 生成点阵
	function renderDiv() {
		$dots.innerHTML = ''
		let hex = ''
		data8.forEach((dotOne,row)=>{
			dotOne.forEach((dot,col)=>{
				let div = document.createElement('div')
				div.setAttribute('data-row',row)
				div.setAttribute('data-col',col)
				div.className = dot==1 ? 'red':''
				$dots.appendChild(div)
			})
			// 输出的二进制和keyes 的点阵位置相反，需要翻转一下
			hex += binaryToHex([...dotOne].reverse().join(''))
		})
		$hex.value = "b'"+hex+"'"
	}
	// 二进制转16进制
	function binaryToHex(binary) {
		let hex = parseInt(binary, 2).toString(16)
		hex = hex < 10 ? '0'+hex : hex
		hex = '\\x'+hex
		return hex;
	} 
	renderDiv()
	$dots.onclick = (e)=>{
		let target = e.target;
		if (target.className != 'dots') {
			let {row,col} = target.dataset;
			data8[row][col] = Number(!data8[row][col])
			renderDiv()
		}

	}
	$btn.onclick = ()=> {
	    $hex.select()
	    document.execCommand('copy')
	    $hex.blur()
	}
</script>
</html>